#!/bin/sh

. "$SPEC_PATH/abstract/dbops-restart"

e2e_test_extra_hash() {
  "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" path_hash \
    "$(realpath --relative-to "$PROJECT_PATH" "$SPEC_PATH/abstract/dbops-restart")"
}

e2e_test() {
  run_test "Checking that restart timeout works correctly" check_restart_timed_out

  run_test "Checking that restart can be repeated if failed" check_restart_repeat
}

check_restart_timed_out() {
  reset_cluster
  trigger_cluster_require_restart

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: restart
  timeout: PT1S
  restart:
    method: InPlace
EOF

  if kubectl wait --timeout "$((E2E_TIMEOUT * 2))s" -n "$CLUSTER_NAMESPACE" sgdbops "$DBOPS_NAME" \
    --for condition=Completed \
    && kubectl wait --timeout "0s" -n "$CLUSTER_NAMESPACE" sgdbops "$DBOPS_NAME" \
    --for condition=Failed
  then
    success "restart failed."
  else
    fail "restart did not fail."
  fi

  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"

  wait_pods_running "$CLUSTER_NAMESPACE" 3
  wait_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"

  check_mock_data_samehost "$CLUSTER_NAME"
  wait_until check_mock_data_replication "$CLUSTER_NAME"
}

check_restart_repeat() {
  trigger_cluster_require_restart
  set_restarted_pods

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: restart
  restart:
    method: InPlace
EOF

  check_restart

  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"
}
